﻿
<style type="text/css">

    input[type=text]
    {
        width: 15em;
    }

   input[type=number]
   {
       width: 4em;
   }

    .lineChartWatermark {
        position: absolute;
        left: 40px;
        top: 20px;
        font-weight: bold;
    }

</style>

<div>
    
     <!--   Width: <input id="width" value="400"/>px,
        Height: <input id="height" value="210"/>px, -->
        Catalog: <select id="DataSetSelect"></select>
       <input id="GalaxySearch" type="text" placeholder="Galaxy"/>
       <input id="Distance" type="number" placeholder="r" min="0"/>
    Type? <select id="Is3D">
        <option value="0">2D</option>
        <option value="1">3D</option>
    </select>
       Secondary Filter: <select id="NeighborFilter"></select>
        
    
        
        <span id="DrawButton" class="button" data-icon="fa-picture-o" style="display:none;">Generate</span>
    <span id="working" style="display:none;"><i class="fa-fw fa fa-spin fa-spinner"></i> Working</span>
    <span class="button" data-icon="fa-trash-o" onclick="resetPlot();">Clear</span>
      <span id="SaveButtons">
          <!---  <span id="SaveButton" class="button" data-icon="fa-save">Save Image Plot</span> -->
             <span id="SaveButtonChart">Save Chart</span> 
        </span>
    
    
</div>

    


<div style="float: left; position: relative; margin-left: 15px;" class="ui-widget">
    <div class="ui-widget-header">Pointwise Dimension Plot</div>
    <div class="ui-widget-content" style="padding: 5px;">
        <div id="placeholder" style="width: 1000px; height: 500px;"></div>
    </div>
</div>

<div class="ui-widget ml" style="float: left; position: relative;">
    <div class="ui-widget-header">Data Series</div>
    <div class="ui-widget-content" id="PDLegend"></div>
</div>

<!--
<div class='ui-widget' id="ImageWidget" style="width: 700px; height: 720px; float: left;">
    <div class='ui-widget-header'>Generated Image</div>
    <div class='ui-widget-content'>
        <canvas id='c' />
    </div>
</div>

    -->


<script type="text/javascript">

    ///<reference path="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" />
    ///<reference path="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js" />
    ///<reference path="js/lib.js" />
    ///<reference path="js/md5.js" />
    ///<reference path="js/jCanvas.min.js" />



    var GalaxyId = "";
    var GalaxyName = "";
    
    var offsetPoints;// = GetRandomOffsets(c, targetRandomPoints);
    var offsetsMaxX, offsetsMaxY;
    var largestAbsXOffset = 0;
    var largestAbsYOffset = 0;
    var startGalaxy;
    var dataCatalog;

    function UpdateFilters() {
        var dataSetId = $("#DataSetSelect > option:selected").val();
        GetJsonSproc("usp_GetMorphologyFilters",
           {
               DataSetId: dataSetId
           },
       function (json) {
           var sel = $("#NeighborFilter");

           sel.empty();

          // var o = $("<option>").text("All").val("");
         //  sel.append(o);

           $.each(json, function (key, value) {
              // console.dir(value);
               var o = $("<option>").text(value.Name).val(value.RegexFilter);
               sel.append(o);
           });

       });

      //  cahceDataForPlot();
    }

    $(document).ready(function ()
    {

        $("#GalaxySearch").autocomplete(
           {
               minLength: 3,
               source: function(request, response)
               {
                   var dataSetId = $("#DataSetSelect > option:selected").val();
                   GetJsonSproc("usp_searchgalaxybyname",
                       {
                           wildcard: request.term,
                           DataSetId: dataSetId
                       },
                       function (json)
                       {
                           response(json);
                       });
               },
               select: function(event, ui)
               {
                   event.preventDefault();
                   $("#DrawButton").show();
                   //console.dir(ui);
                   //alert(ui.item.label);
                   $("#GalaxySearch").val(ui.item.label);
                   GalaxyId = ui.item.value;
                   GalaxyName = ui.item.label;
                   
               }
           });
     

        $("#DrawButton").click(function () { /*LoadOffsets(); */ Chart(); });

        $("#SaveButton").click(function () { SaveImage(); });
        $("#SaveButtonChart").click(function () { SaveImageChart(); });

        $("#SaveButtons").hide();


        $("#ImageWidget").resizable(
            {
                alsoResize: "#ImageWidget .ui-widget-content, #ImageWidget canvas",
                //  animate: true,
                start: function (evt, ui)
                {
                    //$("#ImageWidget canvas").hide();
                },
                stop: function (evt, ui)
                {
                    //            $("#ImageWidget canvas").show();
                    RescaleOffsets();
                    draw();
                }
            });

       
        GetJsonSproc("usp_GetDataSets",

           function (json) {

               var sel = $("#DataSetSelect");
               sel.empty();
               sel.change(UpdateFilters);

               $.each(json, function (key, value) {
                //   console.dir(value);
                   var o = $("<option>").text(value.Name).val(value.ID);
                   sel.append(o);
               });
               UpdateFilters();
           });
        
      //  PreparePlot();
    });


    /*
    function LoadOffsets()
    {

        Distance = $("#Distance").val();
      //  var GalaxyId = $("#GalaxyId").val();
        dataCatalog = $("#DataSetSelect option:selected").text();

        var param =
            {
                startobject: GalaxyId,
                distance: Distance
            }

        if ($("#NeighborFilter > option:selected").val() != "") {
            param.SecondaryRegex = $("#NeighborFilter > option:selected").val();
        }

        GetJsonSproc("usp_GetNearbyObjects", 
         param   
        ,
        function (json)
        {               
            SizeCanvas();
            var c = $("#c");

            var xCenter = Math.round(c.width() / 2);
            var yCenter = Math.round(c.height() / 2);

            var minX = 0 - xCenter;
            var maxX = c.width() - xCenter;

            var minY = 0 - yCenter;
            var maxY = (c.height() - 20) - yCenter; // take 20px off max height to not step on watermark
            
            var points = new Array();

          //  console.log(json[0]);

            var x0 = json[0].glon;
            var y0 = json[0].glat;           
            startGalaxy = json[0];
     
            largestAbsXOffset = 0;
            largestAbsYOffset = 0;

            //console.log("newxRatio " + newXRatio);
            //console.log("newYRatio " + newYRatio);

            for (var i = 1; i <= json.length-1; i++)
            {
                var item = json[i];                
                //  console.log(item);
                var p = {
                    xOffset: (x0 - item.glon),//) * newXRatio,
                    yOffset: (y0 - item.glat) // * newYRatio,
                   // Name : json.GalaxyName
                };

                points.push(p);

                var absXOffset = Math.abs(p.xOffset);
                var absYOffset = Math.abs(p.yOffset);

                if (absXOffset > largestAbsXOffset)
                    largestAbsXOffset = absXOffset;

                if (absYOffset > largestAbsYOffset)
                    largestAbsYOffset = absYOffset;

                

            }
            

            offsetPoints = points;
            RescaleOffsets();
            draw();           


        });
    }*/


    function UpdateOffsets()
    {
       //  alert("updateOffsets");
        offsetPoints = GetRandomOffsets(targetRandomPoints);
    }

    function SaveImage()
    {
        /*var c = $("#c");    
        var img = new Image();    
        img.src = c.getCanvasImage("png");
        $("#imgHolder").append(img);*/
        var canvas = document.getElementById("c");
        window.open(canvas.toDataURL());
    }

    function SaveImageChart()
    {
        var canvas = $("#placeholder").data("plot").getCanvas();
        window.open(canvas.toDataURL());
    }

    function GetWatermarkString(n) 
    {
        var f = $("#NeighborFilter > option:selected").text();
        return dataCatalog + " | " + startGalaxy.GalaxyName + " glon=" + startGalaxy.glon + "° glat=" + startGalaxy.glat + "° r=" + Distance + "° n=" + n + " f=" + f + " | Galactic (http://galactic.codeplex.com)";
    }


    function watermark(c, h)
    {
        var bottom = h;
        //alert("bottom: " + bottom);
        c.drawText(
            {
                strokeStyle: "#000",
                strokeWidth: 1,
                x: 5,
                y: bottom - 10,
                fontFamily: "arial",
                //fontStyle: "bold",
                fontSize: "12px",
                text: GetWatermarkString(offsetPoints.length), // this data does not have source galaxy
                align: "left",
                respectAlign: true

            });

    }

    function drawDot(c, x, y, color)
    {

        //$("#status").append(" dot at " + x + ", " + y);
        color = (color != null) ? color : "#000";

        c.drawArc({
            fillStyle: color,
            strokeWidth: 1,
            x: x,
            y: y,
            radius: 1

        });
    }

    function getRandomInt(min, max)
    {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function RescaleOffsets()
    {
        var c = $("#c");

        var xCenter = Math.round(c.width() / 2);
        var yCenter = Math.round(c.height() / 2);

        var minX = 0 - xCenter;
        var maxX = c.width() - xCenter;

        var minY = 0 - yCenter;
        var maxY = (c.height() - 20) - yCenter; // take 20px off max height to not step on watermark


        // padding on edge of image.
        minX += 5;
        maxX -= 5;
        
        minY += 5;
        maxY -= 5;
        

        var newXRatio;
        var newYRatio;

        //rescale x

        newXRatio = maxX / largestAbsXOffset;
        newYRatio = maxY / largestAbsYOffset;

        //alert(newXRatio + "\n" + newYRatio);

        for (var i = 0; i < offsetPoints.length; i++)
        {
            var p = offsetPoints[i];
            p.xOffset *= newXRatio;
            p.yOffset *= newYRatio;
        }

        offsetsMaxX = maxX;
        offsetsMaxY = maxY;
    }
    /*
    function GetRandomOffsets(target)
    {
        //alert("GetRandomOffsets");
        SizeCanvas();
        var c = $("#c");

        var xCenter = Math.round(c.width() / 2);
        var yCenter = Math.round(c.height() / 2);

        var minX = 0 - xCenter;
        var maxX = c.width() - xCenter;

        var minY = 0 - yCenter;
        var maxY = (c.height() - 20) - yCenter; // take 20px off max height to not step on watermark

        offsetsMaxY = maxY;
        offsetsMaxX = maxX;

        var points = new Array();

        for (var i = 1; i <= target; i++)
        {
            points.push(
            {
                xOffset: getRandomInt(minX, maxX),
                yOffset: getRandomInt(minY, maxY)
            });
        }
        return points;
    }
    */
    function SizeCanvas()
    {
        //alert("sizeCanvas");
        var canvas = $("#c");
        var w = $("#ImageWidget");
        w.show();
        boxWidth = (w.first(".ui-widget-content").css("width"));
        boxHeight = (w.first(".ui-widget-content").css("height"));
        var w = parseInt(boxWidth) - 20;
        var h = parseInt(boxHeight) - 40;
        //  alert(boxWidth + ", " + boxHeight);
        //  alert(w + ", " + h);

        targetRandomPoints = $("#targetCount").val();


        //alert("size before w/h");    
        //alert(canvas);
        canvas.attr("width", w + "px");
        canvas.attr("height", h + "px");



        //   alert(w.css("width") + ", " + w.css("height"));    


        return { w: w, h: h };

    }

    function draw()
    {
        //alert("start draw");
        var dimensions = SizeCanvas();
        var w = dimensions.w;
        var h = dimensions.h;

        var xCenter = Math.round(w / 2);
        var yCenter = Math.round(h / 2);



        //alert("draw c");
        var canvas = $("#c");
        canvas.clearCanvas();

        canvas.drawRect(
           {
               fillStyle: "#fff",
               x: 0,
               y: 0,
               width: w,
               height: h,
               fromCenter: false
           });

        drawDot(canvas, xCenter, yCenter, "red");

      //  console.log(offsetPoints);

        for (var i = 0; i < offsetPoints.length; i++)
        {
            var point = offsetPoints[i];
            var x = xCenter + point.xOffset;
            var y = yCenter + point.yOffset;
            drawDot(canvas, x, y, "#000");
        }

        watermark(canvas, h);

        $("#SaveButtons").show();

    }

    var _plotSeries = [];
   
    var plot;

    var options =
       {
           axisLabels: {
               show: true
           },
           legend:
               {
                   show: true,
                   position: "ne",
                   container: $("#PDLegend")
               },
          
           series:
              {
                  // lines: { show: true },
                  points: { show: true, radius: 1 },
                  // data: chartData,
                  // color: "black"
              },
           xaxis:
               {
                   //   min: 0,
                   // max: 360,
                   // reserveSpace: false
                   axisLabel: "log &theta;",
                   position: 'bottom'
               },

           yaxis:
               {
                   //  min: -90,
                   //  max: 90,
                   //  reserveSpace: true
                   axisLabel: "log N(< &theta;)",
                   position: 'left',
               }
       };

    function PreparePlot()
    {
        plot = $.plot($("#placeholder"), _plotSeries, options);
     //   console.dir(plot);
    }

    function resetPlot()
    {
        _plotSeries = [];
        PreparePlot();
    }

    function Chart()
    {
        $("#working, #DrawButton").toggle();

        Distance = $("#Distance").val();
      //  var GalaxyId = $("#GalaxyId").val();

        var placeholder = $("#placeholder");        
       // placeholder.height(placeholder.data("orgHeight"));
      //  placeholder.parents(".ui-widget").hide();

        var param =
            {
                startobject: GalaxyId,
                DataSetId: $("#DataSetSelect > option:selected").val(),
                FittingRange: Distance
            }

       
        param.SecondaryRegex = $("#NeighborFilter > option:selected").val();
        param.Is3D = false;
       
            var sproc = "getpointwiseforchart";
            if ($("#Is3D > option:selected").text() == "3D")
                param.Is3D = true;
          
        GetJsonSproc
         (sproc,
            param                
           ,
            function (json)
            {
                console.dir(json);

                var dataForChart = json[0];

               
                var PD = json[1];

               // console.clear();
               // console.log(json);
                
                var chartData = [];

                $.each(dataForChart, function (key, value)
                {
                   // console.log(value)
                    var item = [value.PD_LogDistance, value.PD_LogCount];
                    chartData.push(item)
                });

              //  console.log(chartData);
        
                _plotSeries.push(

                    {
                        label: GalaxyName + " &theta;=" + Distance + " t=" + $("#Is3D > option:selected").text() + " Sf=" + $("#NeighborFilter > option:selected").text() + " PD=" + PD,
                        lines: { show: true },
                        points: { show: true },
                        data: chartData
                    });
                    

              

                var placeholder = $("#placeholder");
                placeholder.parents(".ui-widget").show();
               // placeholder.parent().siblings(".ui-widget-header").text(GetWatermarkString(chartData.length )); // this data includes source gala
               
                PreparePlot();


                $("#working, #DrawButton").toggle();

                var canvas = $("#placeholder").data("plot").getCanvas();

                
               
                
                   
              
                           
            //    var orgHeight = placeholder.height();
             //   placeholder.data("orgHeight", orgHeight);

            //    placeholder.height(placeholder.height() + 20);

                

            });
    }




</script>